import { ref } from 'vue'
import { getCategoryTree, getList } from '/@/api/article/article'

export function useArticle() {
  const categoryOptions = ref<Array<any>>([])
  const loadTab = ref<any>({})
  const articleListObj = ref<any>({})

  getCategoryTree().then((res) => {
    categoryOptions.value = res.data.data
    const categoryId = categoryOptions.value[0].id
    if (categoryId) {
      getList(1, 30, {
        categoryId: categoryId,
      }).then((res) => {
        articleListObj.value[categoryId] = res.data.data.records
      })
    }
  })

  const beforeChange = (index: number) => {
    const categoryId = categoryOptions.value[index].id
    // 返回 Promise 来执行异步逻辑
    return new Promise((resolve) => {
      // 在 resolve 函数中返回 true 或 false
      if (categoryId) {
        // 加载过阻止此次切换
        if (loadTab.value[index]) {
          //
        } else {
          loadTab.value[index] = true
          getList(1, 30, {
            categoryId: categoryId,
          }).then((res) => {
            articleListObj.value[categoryId] = res.data.data.records
          })
        }
      }
      resolve(true)
    })
  }

  return {
    categoryOptions,
    loadTab,
    articleListObj,
    beforeChange,
  }
}
